import React, { FC } from "react";
import { Typography, Space,Form,Input, Button, message } from "antd";
import styles from './Register.module.scss'
import { UserAddOutlined } from "@ant-design/icons";
import { Link,useNavigate } from "react-router-dom";
import { LOGIN_PATHNAME } from "../router";
import { useRequest } from "ahooks";
import { register } from "../utils/api";
const { Title } = Typography
const Register: FC = () => {
    const nav=useNavigate()
    const { run:registerHandle } = useRequest(async (val) => {
        const { username, password, nickname } = val
        register(username,password,nickname)
    }, {
        manual: true,
        onSuccess() {
            message.success('注册成功')
            nav(LOGIN_PATHNAME)
        }
    })
    const onFinish = (values: any) => {
        registerHandle(values);
        }
    return <div className={styles.container}>
        <Space>
        <Title level={2}><UserAddOutlined/></Title>
        <Title level={2}>注册</Title>
        </Space>
        <Form onFinish={onFinish}
            labelCol={{ span: 6 }}
            wrapperCol={{span:18}}
        >
            <Form.Item label='用户名' name='username'
              rules={[{ required: true, message: "请输入用户名" },
                { type: 'string', min: 5, max: 20, message: "用户名长度在5-20之间" },
            {pattern:/^\w+$/,message:'只能是字母数字下划线'}
        ]}>
                <Input/>
            </Form.Item>
            <Form.Item label='密码' name='password'
             rules={[{ required: true, message: "请输入密码" },
        ]}
            >
                <Input.Password/>
            </Form.Item>
            <Form.Item label='确定密码' name='confirmPassword'
             rules={[{ required: true, message: "请输入密码" },
                ({ getFieldValue }) => ({
                    validator(_, value) {
                        if (!value || getFieldValue('password')===value) {
                            return Promise.resolve()
                        } else {
                            return Promise.reject(new Error('两次密码不一致'))
                        }
                 }
             })
        ]}
            >
                <Input.Password/>
            </Form.Item>
            <Form.Item label='昵称' name='nickname'>
                <Input/>
            </Form.Item>
            <Form.Item wrapperCol={{offset:6,span:16}}>
                <Space>
                    <Button type="primary" htmlType="submit">注册</Button>
                    <Link to={LOGIN_PATHNAME}>已有账户,登录</Link>
                </Space>
            </Form.Item>
    </Form>
    </div>
}
export default Register